package net.jqsoft.common.lang;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class IoTools {

	public static final Logger LOGGER = LoggerFactory.getLogger(IoTools.class);

	/**
	 * inputStream转字节数组
	 * 
	 * @throws IOException
	 */
	public static byte[] inputStreamToBytes(InputStream inputStream) throws IOException {
		ByteArrayOutputStream output = null;
		byte[] buffer = null;
		try {
			output = new ByteArrayOutputStream();
			buffer = new byte[1024];
			int n = 0;
			while ((n = inputStream.read(buffer)) != -1) {
				output.write(buffer, 0, n);
			}
			return output.toByteArray();
		} finally {
			buffer = null;
			if (null != output)
				close(output);
			if (null != inputStream)
				close(inputStream);
		}
	}

	/**
	 * 字节数组转inputStream
	 * 
	 * @throws IOException
	 */
	public static InputStream bytesToInputStream(byte[] bytes) {
		return new ByteArrayInputStream(bytes);
	}

	public static String getMD5(InputStream is) throws NoSuchAlgorithmException, IOException {
		StringBuffer md5 = new StringBuffer();
		MessageDigest md = MessageDigest.getInstance("MD5");
		byte[] dataBytes = new byte[1024];
		int nread = 0;
		while ((nread = is.read(dataBytes)) != -1) {
			md.update(dataBytes, 0, nread);
		};
		byte[] mdbytes = md.digest();
		for (int i = 0; i < mdbytes.length; i++) {
			md5.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
		}
		dataBytes = null;
		return md5.toString();
	}
	
	public static String getMD5(byte[] bytes) throws NoSuchAlgorithmException, IOException {
		StringBuffer md5 = new StringBuffer();
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(bytes);
		byte[] mdbytes = md.digest();
		for (int i = 0; i < mdbytes.length; i++) {
			md5.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
		}
		return md5.toString();
	}
	
	/**
	 * 文件转base64字符串
	 */
	public static String fileToBase64(InputStream inputStream) throws IOException{
		return new BASE64Encoder().encode(inputStreamToBytes(inputStream));
	}
	
	/**
	 * base64字符串转InputStream
	 */
	public static byte[] base64ToBytes(String base64) throws IOException{
		byte[] b = new BASE64Decoder().decodeBuffer(base64);
		for (int i = 0; i < b.length; ++i) {
			if (b[i] < 0) {// 调整异常数据
				b[i] += 256;
			}
		}
		return b;
	}
	
	
	/**
	 * base64字符串转InputStream
	 */
	public static InputStream base64ToInputStream(String base64) throws IOException{
		return new ByteArrayInputStream(base64ToBytes(base64));
	}	
	

	/**
	 * 关闭流
	 */
	public static void close(Closeable closeable) {
		if (null != closeable) {
			try {
				closeable.close();
			} catch (IOException e) {
				LOGGER.error(e.getMessage(), e);
			}
		}
	}
	
}